package com.jxwifi.cloud.quickcleanserver.main;

import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RidePath;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.idroid.widget.LoadDialog;
import com.jxwifi.cloud.quickcleanserver.R;
import com.jxwifi.cloud.quickcleanserver.adapter.WorkbenchListAdapter;
import com.jxwifi.cloud.quickcleanserver.app.AccountMgr;
import com.jxwifi.cloud.quickcleanserver.app.UrlPool;
import com.jxwifi.cloud.quickcleanserver.bean.OrderFromBean;
import com.jxwifi.cloud.quickcleanserver.okhttp.AuzHttp;
import com.jxwifi.cloud.quickcleanserver.okhttp.DataJson_Cb;
import com.jxwifi.cloud.quickcleanserver.okhttp.Params;
import com.jxwifi.cloud.quickcleanserver.utils.LazyLoadFragment;
import com.jxwifi.cloud.quickcleanserver.utils.LocationGaoDe;
import com.jxwifi.cloud.quickcleanserver.utils.PasswordLogin;
import com.jxwifi.cloud.quickcleanserver.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.trinea.android.common.util.ListUtils;

/**
 * 工作台
 * Created by Administrator on 2019/5/13.
 */

public class WorkbenchFragment extends LazyLoadFragment implements SwipeRefreshLayout.OnRefreshListener ,RouteSearch.OnRouteSearchListener{

    private String TAG = this.getClass().getSimpleName();
    @Bind(R.id.img_workbench_head_images)
    TextView mImgWorkbenchHeadImages;
    @Bind(R.id.srl_fg_workbench_list)
    SwipeRefreshLayout mSrlFgWorkbenchList;
    @Bind(R.id.rv_workbench_list)
    RecyclerView mRvWorkbeanchList;
    @Bind(R.id.rel_null_data)
    RelativeLayout mRelNullData;

    private WorkbenchListAdapter mAdapter;
    private int mPageIndex = 1;//页数
    private int mLastVisibleItemIndex;//用于记录滑动监听中Item的位置
    private int mTotalNum;//记录接口中的总条数（如果没有返回这个字段也可以不适用）
    private LinearLayoutManager mLayoutManager;
    //表示是否可以上拉刷新.因为APP中上拉刷新没有添加动画效果，在数据加载的时候，会多次请求上拉刷新的判断，导致数据没加载完成前，再次的执行了数据请求方法
    //数据页数是根据请求的次数叠加的，就会出现数据为空的情况，特加这个字段做判断
    private boolean mIsrefresh = true;
    private LoadDialog mLoadDialog;//加载动画
    public RouteSearch  mRouteSearch;
    private int workPosition = 0;
    private List<OrderFromBean> mrecords;
    private boolean isVisiableWork;


    public int setContentView() {
        mLoadDialog = new LoadDialog(mBaseContext, "");
        return R.layout.fragment_workbench;
    }

    @Override
    protected void lazyLoad() {
        if (AccountMgr.isLogin(mBaseContext)) {
            initView();
            onRefresh();
        }
    }

    @Override
    protected void stopLoad() {
        Log.w("oushuhua", "WorkbenchFragment" + "已经对用户不可见，可以停止加载数据");
    }


    @OnClick({R.id.tv_null_data_refresh})
    void clickCK(View v) {
        switch (v.getId()) {
            case R.id.tv_null_data_refresh:
                mLoadDialog.show();
                mRelNullData.setVisibility(View.GONE);
                mSrlFgWorkbenchList.setVisibility(View.GONE);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        onRefresh();
                        mLoadDialog.dismiss();
                    }
                }, 1500);
                break;
        }
    }

    private void initView() {
        mRvWorkbeanchList.setLayoutManager(mLayoutManager = new LinearLayoutManager(mBaseContext));
        mRvWorkbeanchList.setAdapter(mAdapter = new WorkbenchListAdapter(mBaseContext, TAG));
        mSrlFgWorkbenchList.setColorSchemeColors(0xfffe8026);
        mSrlFgWorkbenchList.setOnRefreshListener(this);
        /**
         * 上拉刷新监听方法（在RecyclerView控件中实现这个方法）
         */
        mRvWorkbeanchList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                if (newState == RecyclerView.SCROLL_STATE_IDLE && mLastVisibleItemIndex + 1 == mAdapter.getItemCount() &&
                        mAdapter.getItemCount() < mTotalNum && mIsrefresh) {
                    mIsrefresh = false;
                    onLoadMore();
                }
            }

            /**
             * 监听滑动中的时候Item的位置
             */
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                mLastVisibleItemIndex = mLayoutManager.findLastVisibleItemPosition();
            }
        });

    }

    @Override
    public void onRefresh() {
        mPageIndex = 1;
        getList();
    }

    private void onLoadMore() {
        mPageIndex++;
        getList();
    }

    public void getList() {
        if(!isVisiableWork){
            return;
        }
        if (LocationGaoDe.getLatitude() == 0.0) {
            return;
        }
        if (!AccountMgr.isLogin(mBaseContext)) {
            return;
        }
        mSrlFgWorkbenchList.setRefreshing(true);
        Params params = new Params();
        params.add("cityCode", LocationGaoDe.getCityCode());
        params.add("lat", LocationGaoDe.getLatitude());
        params.add("lon", LocationGaoDe.getLongitude());
        params.add("page", mPageIndex);
        params.add("limit", 10);
        AuzHttp.post(UrlPool.GET_LIST_WORK_SPACE, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                mSrlFgWorkbenchList.setRefreshing(false);
                mIsrefresh = true;
                if (code == 0) {
                    JSONObject obj = JSON.parseObject(data);
                    String str = obj.getString("records");
                    mTotalNum = obj.getInteger("total");
                    mrecords = JSON.parseArray(str, OrderFromBean.class);
                    Log.i(TAG,"getList ==> mrecords.size() = "+mrecords.size());
                    if (ListUtils.isEmpty(mrecords) || mrecords == null) {
                        mRelNullData.setVisibility(View.VISIBLE);
                        mSrlFgWorkbenchList.setVisibility(View.GONE);
                        mAdapter.updata();
                    } else {
                        mRelNullData.setVisibility(View.GONE);
                        mSrlFgWorkbenchList.setVisibility(View.VISIBLE);
                        setRideData(0);
                        /*if (mPageIndex > 1) {
                            mAdapter.addData(mrecords);
                        } else {
                            mAdapter.refresh(mrecords);
                        }*/
                    }
                } else {
                    PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin) {
                        getList();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                mSrlFgWorkbenchList.setRefreshing(true);
                mIsrefresh = true;
                Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast, 3000);
            }
        }, TAG);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (AccountMgr.isLogin(mBaseContext)) {
            mRouteSearch = new RouteSearch(mBaseContext);
            mRouteSearch.setRouteSearchListener(this);
            onRefresh();
            Log.i(TAG,"onResume()");
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (AccountMgr.isLogin(mBaseContext)) {
            if (mAdapter != null)
                mAdapter.getCloseTime();
        }
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {

    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {
        if (i == 1000) {
            RidePath ridePath = rideRouteResult.getPaths().get(0);
            //setRideRoute(ridePath, rideRouteResult.getStartPos(), rideRouteResult.getTargetPos());
            float distance = ridePath.getDistance() / 1000;
            long duration = ridePath.getDuration() / 60;
            Log.i(TAG,"workPosition = "+workPosition);
            mrecords.get(workPosition).setRideDistance(distance);
            mrecords.get(workPosition).setRideDuration(duration);
            Log.i(TAG, "onRideRouteSearched ==> " + workPosition + " 距离/公里：" + distance + " 时间/分：" + duration + " getRideDistance = " + mrecords.get(workPosition).getRideDistance()+" workPosition = "+workPosition);
            workPosition++;
            setRideData(workPosition);
            if (workPosition == mrecords.size()) {
                workPosition = 0;
            }

        } else {
            Log.i(TAG, "onRideRouteSearched: 路线规划失败");
        }
    }

    private void setRideData(int position){

        if (position<mrecords.size()){
            RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                    new LatLonPoint(LocationGaoDe.getLatitude(),LocationGaoDe.getLongitude()),
                    new LatLonPoint(Double.valueOf(mrecords.get(position).getLat()), Double.valueOf(mrecords.get(position).getLon())));
            RouteSearch.RideRouteQuery query = new RouteSearch.RideRouteQuery(
                    fromAndTo, RouteSearch.RIDING_DEFAULT);
            mRouteSearch.calculateRideRouteAsyn(query);
        }else{
            if (mPageIndex > 1) {
                mAdapter.addData(mrecords);
            } else {
                mAdapter.refresh(mrecords);
            }
        }
    }

    @Override
    protected void hiddenChange(boolean hidden) {
        super.hiddenChange(hidden);
        isVisiableWork = hidden;
        Log.i(TAG,"hiddenChange ==> hidden = "+hidden);
    }
}
